package bbs.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 *
 * 针对日志 的切面
 * @author ljg;
 * @create 2022-06-07 15:47
 */

@Component
@Aspect
public class LogAspect {
    /**
     * 使用日志 记录 ControllerExceptionAspect
     */
    Logger logger = LoggerFactory.getLogger(ControllerExceptionAspect.class);
    /**
     * 声明一个 切点
     */
    @Pointcut("execution(* bbs.controller.*.*(..))")
    public void pointCut(){}

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Object target = joinPoint.getTarget();
        Object[] args = joinPoint.getArgs();
        //方法名
        String name = joinPoint.getSignature().getName();
        String info = target + "中的" + name + "执行了，传递了 " + Arrays.toString(args) ;
        logger.info(info);
        Object proceed = joinPoint.proceed();
        String after = target +"中的"+ name +"执行完毕，方法的返回值是 ："+ proceed ;
        logger.info(after);
        return proceed;
    }

    @AfterThrowing(value = "pointCut()",throwing = "exception")
    public void afterThrowing(JoinPoint joinPoint, Throwable exception){
        String infos = joinPoint.getTarget() + " 中的 " + joinPoint.getSignature().getName()
                + "执行了, 传递了" + Arrays.deepToString(joinPoint.getArgs())
                + "，抛出的异常 是 : " + exception;
        logger.info(infos);
    }
}
